<?php
/**
 +------------------------------------------------------------------------------
 * OrderAction控制器类
 +------------------------------------------------------------------------------
 * @category   SubAction
 * @package  app
 * @subpackage  Action
 * @author   朝闻道 <admin@iic.cn>
 * @date 2013-6-5
 * @time  下午12:01:54
 +------------------------------------------------------------------------------
 */
class OrderAction extends BaseAction {
	protected $line = '';
	protected $ods = '' ,$newpro,$order;
	// 云购商的手续费 及云购店的手续费
	protected $fee, $small_fee;
	protected $cw,$vcw;
	/**
	 * 载入订单查询类
	 * @date 2013-6-5
	 * @time 下午1:48:31
	 */
	function _initialize() {
		// 载入订单查询类
		parent::_initialize ();
		import ( 'Com.OrderSelect' );
		import('Com.Newpro');
		import('Com.Order');
		$this->newpro = new Newpro();
		$this->ods = new OrderSelect ();		
		$status = array ();
		$status ['-1'] = '审核不通过';
		$status ['0'] = '待审核';
		$status ['1'] = '已审核';
		$status ['2'] = '已完成';
		$status ['-2'] = '已退款';
		$status ['3'] = '备货中';
		$status ['4'] = '已退货';
		$status ['5'] = '已发货';
		$status ['-5'] = '已退货';
		$status ['-1'] = '审核不通过';
		$status ['8'] = '已签收';
		$status ['10'] = '已完成';
		$status ['-10'] = '已取消';
		$this->assign ( 'status', $status );
		$pay_status = array ();
		$pay_status ['0'] = '未支付';
		$pay_status ['1'] = '付款中';
		$pay_status ['2'] = '已付款';
		$pay_status ['3'] = '申请退款';
		$pay_status ['4'] = '己退款';
		$this->assign ( 'pay_status', $pay_status );
		$shipping_status = array ();
		$shipping_status ['0'] = '未发货';
		$shipping_status ['1'] = '已发货';
		$shipping_status ['2'] = '已收货';
		$shipping_status ['3'] = '申请换货';
		$shipping_status ['4'] = '己换货';
		$shipping_status ['5'] = '发货中';
		$this->assign ( 'shipping_status', $shipping_status );
		
		
		
		$this->cw =array();
		$this->vcw= array(
				'guo999','edwin','adminwei','guojiacheng','janson','caiwusmw','guan100221',
				'zhangruizhuan','fy123','joy123','yunyingjiang','15815525119',
				'chencui','kefu_zhanghui','kefu_zhaowei','kefu_gaofang',
				'18033328198','wuguihua','yhf1979',
				'zhongzhiwei','wufang','15361880999','chenyq','18680660768','zhuzhijun'
		);
	
		// add by tb 暂时
		if (!in_array( $this->username, $this->vcw, true ) ) {
			$this->_ajm ( 300, '权限不足!', 0 );
			exit;
		}
		
		self::_set_fee ();
	} // end _initialize
	
	/**
	 * 订单一览
	 * @date 2013-6-5
	 * @time 下午1:51:12
	 */
	function index() {
		// 订单一览
		$where = array ();
		$count = $this->ods->order_list ( $where, 'all' );
		$this->assign ( "totalCount", $count );
		if ($count > 0) {
			$page = new Page ( $count, $this->listrows );
			$pages = $page->show ();
			$list = $this->ods->order_list ( $where, $page->firstRow . ',' . $page->listRows );
			$this->assign ( 'list', $list );
		}
		$this->display ();
	} // end index
	
	/**
	 * 云采购的订单
	 * @date 2013-6-21
	 * @time 下午2:46:37
	 */
	function smw() {
		$condtion = array();
		$condtion['platform'] = 'SMW01';
		if($_REQUEST['now_ord']){
			$condtion['o.status']=1;
// 			$condtion['mtime'] = array('between',array($time['stime'],$time['etime']));
			$time['stime'] = gettime(date('Y-m-d 00:00:00',time()));
			$time['etime'] = gettime(date('Y-m-d 23:59:59',time()));
			$condtion = parent::create_date($time,'mtime',$condtion);
		}else {
			
			if($_REQUEST['status']!=='' && $_REQUEST['status'] !== null && $_REQUEST['status']!== 'select'){
				$condtion['o.status'] = $_REQUEST['status'];
				$map['status'] = $_REQUEST['status'];
			}else{
				$map['status'] = 'select';
			}
			
			if($_REQUEST['pay_status']!=='' && $_REQUEST['pay_status'] !== null && $_REQUEST['pay_status']!== 'select'){
				$condtion['pay_status'] = $_REQUEST['pay_status'];
				$map['pay_status'] = $_REQUEST['pay_status'];
			}else{
				$map['pay_status'] = "select";
			}
			
			if($_REQUEST['shipping_status']!=='' && $_REQUEST['shipping_status'] !== null && $_REQUEST['shipping_status']!== 'select'){
				$condtion['shipping_status'] = $_REQUEST['shipping_status'];
				$map['shipping_status'] = $_REQUEST['shipping_status'];
			}else{
				$map['shipping_status'] = 'select';
			}
	
			$condtion = parent::create_where($condtion);
			$time['stime'] = gettime($_REQUEST['statetime']);
			$time['etime'] = gettime($_REQUEST['endtime']);
			$condtion = parent::create_date($time,'add_time',$condtion);
		}
		
		//$_REQUEST['keywords'] ? $condtion[$_REQUEST['sfield']] =  $_REQUEST['keywords'] : FALSE;
		//$_REQUEST['statetime'] && $_REQUEST['endtime'] ? $condtion['add_time'] = ''.strtotime($_REQUEST['statetime']).','.strtotime($_REQUEST['endtime']).'' : FALSE;
// 		$info = $this->newpro->order_check(array('add_time'=>'1388113000,1388113005'));
// 		dump($info );
// // 		exit;
// 		// 云采购的订单
// 		$sel_status = $_REQUEST ['sel_status'] ? $_REQUEST ['sel_status'] : 'ALL';
// 		$this->assign ( 'sel_status', $sel_status );
// 		$where = array ();
// 		$where ['platform'] = 'SMW01';
// 		if ($sel_status != 'ALL') {
// 			$where ['status'] = $sel_status;
// 		}
		if($_REQUEST['separate']){
			$count = $this->newpro->order_check_separate( $condtion ,$_REQUEST['separate']);
		}else{
			$count = $this->newpro->order_check( $condtion );
		}
// 		dump($count);
		$this->assign ( "totalCount", $count );
		if ($count > 0) {
			$page = new Page ( $count, $this->listrows );
			$pages = $page->show ();
			
			if($_REQUEST['separate']){
				$list = $this->newpro->order_check_separate( $condtion,$_REQUEST['separate'], $page->firstRow . ',' . $page->listRows );
			}else{
				$list = $this->newpro->order_check( $condtion, $page->firstRow . ',' . $page->listRows );
			}
// 			dump($list);
// 			exit();
			foreach ( $list as &$or ) {
				$re = M('order_finance')->field('group_concat(`subject`,FORMAT(`value`/100,2)) as rea' )->where( array('order_id'=>$or['id'],'code'=>'reality') )->find();
				$rem = M('order_finance')->field('value')->where( array('order_id'=>$or['id'],'subject'=>'CV','code'=>'reality') )->find();
				$sp = M('order_finance')->field('group_concat(`subject`,FORMAT(`value`/100,2)) as rea' )->where( array('order_id'=>$or['id'],'code'=>'spotprice') )->find();
				$or['reality'] = $re['rea'];
				$or['reality_value']=$rem['value'];
				$or['spotprice'] = $sp['rea'];
			}
			
			//获取订单快递单号
			$courier_number=$this->ods->order_ext($list);
// 			dump($courier_number);
			$this->assign('courier_number',$courier_number);
			$this->assign ( 'list', $list );
// 			dump($list);
		}
		$this->assign('statetime',$_REQUEST['statetime']);
		$this->assign('endtime',$_REQUEST['endtime']);
		$this->assign('map',$map);
		$oids = arr_to_explode ( $list, 'id' );
		$depot = self::getdepot ( $oids );
		$this->assign ( 'depot', $depot );
		$this->display ();
	} // end smw
	
	/**
	* 
	* @param param_type param 
	* @return return_type
	* @author MaWei (http://www.phpyrb.com)
	* @date 2014-1-9上午11:51:25
	*/
	function out(){
		$orderids = array();
		$orderids = explode(',', array_shift($_REQUEST['b2bids']));
		$temp = $this->newpro->b2b_order_goods($orderids);
		$goods = array();
		foreach ($temp as $k => $v){
			$goods[$v['id']]['id'] = $v['id'];
			$goods[$v['id']]['name'] = $v['product_name'];
			$goods[$v['id']]['price'] = $v['price'] * 0.01;
			$goods[$v['id']]['number'] = $v['number'];
			$goods[$v['id']]['count'] = $v['price'] * $v['number'] * 0.01;
		}
		$path = $this->newpro->goods_xls($goods);
		$this->assign('path',$path);
		$this->display();
	}
	
	
	function confirm_status(){
		$model = M('Order');
		$where = array();
		$where['shipping_status'] = 1;
		$where['id'] = $_REQUEST['id'];
		$data = array();
		$data['status'] = 10;
		$reid = $model->where($where)->save($data);
// 		echo $model->getLastSql();exit;
		if($reid === FALSE){
			$this->_ajm('300','操作失败！',1);
		}else {
			$this->_ajm('200','操作成功！',1);
		}
		
	}
	
	/**
	 * 云购的订单
	 * @date 2013-6-21
	 * @time 下午2:47:13
	 */
	function o2o() {
		// 云购的订单
		$sel_status = $_REQUEST ['sel_status'] ? $_REQUEST ['sel_status'] : 'ALL';
		$this->assign ( 'sel_status', $sel_status );
		$where = array ();
		// $this->ods = new OrderSelect ('91YUNGOU');
		$where ['platform'] = '91YUNGOU';
		if ($sel_status != 'ALL') {
			$where ['status'] = $sel_status;
		}
		$where = self::create_where($where);
		$count = $this->ods->order_list( $where, 'all' );
		$this->assign ( "totalCount", $count );
		if ($count > 0) {
			$page = new Page ( $count, $this->listrows );
			$pages = $page->show ();
			$list = $this->ods->order_list ( $where, $page->firstRow . ',' . $page->listRows, $this->order );
			$list = field2key ( $list, 'id' );
			$list = $this->ods->order_ext ( $list );
// 			dump($list[112099]['ext']);
// 			exit();
			$this->assign ( 'list', $list );
		}
		$this->display ();
	} // end o2o
	
	/**
	 * 订单详情查看
	 * @date 2013-6-26
	 * @time 下午3:16:55
	 */
	function detail() {
		// 订单详情查看
		$orderid = intval ( $_REQUEST ['id'] );
		if (empty ( $orderid )) {
			$this->_ajm ( '300', '参数错误' );
		}
		$data = $this->ods->order_detail ( $orderid );
		if (empty ( $data )) {
			$this->_ajm ( '300', '没有获取到相关的数据' );
		}
		if ($data ['platform'] == '91YUNGOU') {
			self::detailo2o ();
			exit ();
		}
		$map['order_id'] = $_REQUEST['id'];
		$map['element'] = array('in','beizhu,free');
		$res = M('OrderExt')->where($map)->select();
		foreach ($res as $vo){
			switch ($vo['element']){
				case 'beizhu' : 
					$mage['beizhu'] = $vo['value'];
					break;
				case 'free':
					$mage['free'] = $vo['value'];
					break;
			}
		}
		$coupondata = M ()->query ( "select *	from order_coupon where order_id = {$data['id']}" );
		$this->assign ( 'coupondata', $coupondata );
		$this->assign ( 'order', $data );
		$this->assign('mage',$mage);
		$this->display ();
	} // end detail
	
	/**
	 * 订单详情查看
	 * @date 2013-6-26
	 * @time 下午3:16:55
	 */
	function imei() {
		// 订单详情查看
		$orderid = intval ( $_REQUEST ['id'] );
		if (empty ( $orderid )) {
			$this->_ajm ( '300', '参数错误' );
		}
		$data = $this->ods->order_detail ( $orderid );
		if (empty ( $data )) {
			$this->_ajm ( '300', '没有获取到相关的数据' );
		}
		if ($data ['platform'] == '91YUNGOU') {
			self::detailo2o ();
			exit ();
		}
		$map['order_id'] = $_REQUEST['id'];
		$map['element'] = array('in','beizhu,free');
		$res = M('OrderExt')->where($map)->select();
		foreach ($res as $vo){
			switch ($vo['element']){
				case 'beizhu' : 
					$mage['beizhu'] = $vo['value'];
					break;
				case 'free':
					$mage['free'] = $vo['value'];
					break;
			}
		}
		$coupondata = M ()->query ( "select *	from order_coupon where order_id = {$data['id']}" );
		$this->assign ( 'coupondata', $coupondata );
		$this->assign ( 'order', $data );
		$this->assign('mage',$mage);
		$this->display ();
	} // end detail
	
	function imei_do(){
		F('aaaaaa',$_REQUEST);
		
		$data = array();
		foreach ( $_REQUEST['product_id'] as $val ) {
			$val_ = 'imei'.$val;
			foreach ( $_REQUEST[$val_] as $v ) {
				$data[] = array(
					'user_id' => $_REQUEST['user_id'],
					'order_id' => $_REQUEST['order_id'],
					'product_id' => $val,
					'imei' => $v,
					'ctime' => time(),
				);
			}
		}
		F('bbbb',$data);
		$re = M('product_imei')->addAll($data,array(),true);
		echo $re;
		die();
	}
	
	function imei_list(){
		$where = ' where 1';
		$sfield = $_REQUEST['sfield'];
		$keyword = $_REQUEST['keywords'];
		if ( $keyword && $sfield ) {
			if ($_REQUEST['sfield']=='sn') $where .= " and o.sn like '%{$keyword}%' ";
			if ($_REQUEST['sfield']=='username') $where .= " and u.username like '%{$keyword}%' ";
			if ($_REQUEST['sfield']=='imei') $where .= " and i.imei like '%{$keyword}%' ";
			$this->assign('keywords',$keyword);
			$this->assign('sfied',$sfield);
		}
		$re=M()->query( "select count(*) num 
			from product_imei as i left join `user` as u on u.id=i.user_id 
			left join `order` o on o.id=i.order_id
			left join product as p on p.id=i.product_id $where order by o.shipping_time desc" );
		$count = $re[0]['num'];
		$this->assign ( "totalCount", $count );
		if ($count > 0) {
			$page=new Page($count,$this->listrows);
			$list=M()->query( "select i.id,i.imei,p.name,u.username,o.id order_id,o.sn,o.shipping_time,o.pay_time,o.add_time 
				from product_imei as i left join `user` as u on u.id=i.user_id 
				left join `order` o on o.id=i.order_id
				left join product as p on p.id=i.product_id $where order by o.shipping_time desc limit ".$page->firstRow.','.$page->listRows);
// 			echo M()->getLastSql();
			$this->assign('list',$list);
		}
		$this->display();
	}
	
	/**
	 * O2O订单查看页面
	 * @date 2013-9-13
	 * @time 上午11:53:14
	 */
	function detailo2o() {
		// O2O订单查看页面
		$orderid = intval ( $_REQUEST ['id'] );
		if (empty ( $orderid )) {
			$this->_ajm ( '300', '参数错误' );
		}
		$data = $this->ods->o2o_order_detail ( $orderid );
		if (empty ( $data )) {
			$this->_ajm ( '300', '没有获取到相关的数据' );
		}
		// $this->_ajm ( '300', $data);
		$coupondata = M ()->query ( "select * from order_coupon where order_id = {$data['id']}" );
		$this->assign ( 'coupondata', $coupondata );
		$this->assign ( 'order', $data );
		$this->display ( "detailo2o" );
	} // end detailo2o
	
	/**
	 * 批量修改订单状态
	 * @date 2014-04-04
	 * */
	function batchstatus(){
		$ids = $_REQUEST['b2bids'];
		$ids = implode(',', $ids);
		$status = $_REQUEST['status'];
		$field = empty($_REQUEST['field']) ? 'status' : $_REQUEST['field'];
		
		if(!$status || !$ids){
			$this->_ajm(300,'数据传输错误！');
			exit;
		}
		
		$where['id'] = array('in',$ids);
		$data[$field] = $status;
		$data['mtime']=time();
		$model = M ( 'Order' );
		$res = $model->where($where)->save($data);
		
		if($res!==false){
			$this->_ajm(200,'操作成功!',1);
		}else{
			$this->_ajm(300,'操作失败!');
		}
		
	}
	
	
	/**
	 * 修改订单状态
	 * @date 2013-6-28
	 * @time 下午9:33:14
	 */
	function status() {
		// 修改订单状态
		$id = intval ( $_REQUEST ['id'] );
		$status = intval ( $_REQUEST ['status'] );
		// 获取订单当前信息
		$order = M ( 'Order' );
		$data = array ();
		$data ['id'] = $id;
		$info = $order->where ( $data )->find ();
		$sp = M('order_finance')->field('value')->where( array('order_id'=>$info['id'],'code'=>'spotprice','subject'=>'CV') )->find();
		if (empty ( $info )) {
			$this->_ajm ( '300', '订单支付状态修改不成功，没有找到相关的订单信息。' );
		}
		if ($status < $info ['status']) {
			$this->_ajm ( '300', '订单支付状态修改不成功，订单的状态信息不能逆转。' );
		}
		if ($info ['status'] == - 10) {
			$this->_ajm ( '300', '订单已取消。' );
		}
		if (($info ['shipping_status'] != 0) && $status != 10 ) {
			$this->_ajm ( '300', '已发货无需在确认！' );
		}
		$data ['status'] = $status;
		$data ["mtime"] = mktime ();
		$res = $order->save ( $data );
		if ($res === false) {
			$this->_ajm ( '300', '操作失败' );
		}
		
		//********** begin bv by tb 单次采购蛮 1.5w 赠送 100BV *****//
		$sp = M('order_finance')->field('value')->where( array('order_id'=>$info['id'],'code'=>'spotprice','subject'=>'CV') )->find();
		if($sp['value'] >= 1500000 && $status == 10){
			$or_ext['element'] = 'givebv';
			$or_ext['value'] = 1;
			$or_ext['name'] = '赠送BV';
			$or_ext['order_id'] = $info['id'];
			$stat = M('OrderExt')->add($or_ext);
			if ($stat === FALSE) {
				$this->_ajm(300,'可赠送BV，但备注信息写入失败，请把该错误信息及订单号，发给技术部处理！');
		    }
		}	
		//********** end bv by tb 是否能赠送BV ******//
		
		$this->_ajm ( 200, '操作成功', 1 );
	} // end status
	
	/**
	 * 订单取消
	 */
	function cancel() {
		// 修改订单状态
		$id = intval ( $_REQUEST ['id'] );
		// 获取订单当前信息
		$order = M ( 'Order' );
		$data = array ();
		$data ['id'] = $id;
		$info = $order->where ( $data )->find ();
		if (empty ( $info )) {
			$this->_ajm ( '300', '订单支取消失败，没有找到相关的订单信息。' );
		}
		if ($info ['status'] == '-10') {
			$this->_ajm ( '300', '订单已取消。' );
		}
		if ($info ['shipping_status'] != 0) {
			$this->_ajm ( '300', '已发货无法取消！' );
		}
		$data ['status'] = '-10';
		$data ["mtime"] = mktime ();
		$res = $order->save ( $data );
		if ($res === false) {
			$this->_ajm ( '300', '操作失败' );
		}
		$this->_ajm ( 200, '操作成功', 1 );
	} // end status
	
	/**
	 * 验证发货信息
	 */
	function sipping() {
		// 修改订单状态
		$id = intval ( $_REQUEST ['id'] );
		// 获取订单当前信息
		$order = M ( 'Order' );
		$data = array ();
		$data ['id'] = $id;
		$info = $order->where ( $data )->find ();
		if (empty ( $info )) {
			$this->_ajm ( '300', '没有找到相关的订单信息。' );
		}
		if ($info ['status'] <= 0) {
			$this->_ajm ( '300', '发货失败，订单未确定或取消。' );
		}
		if ($info ['pay_status'] == 0) {
			$this->_ajm ( '300', '发货失败，订单未支付。' );
		}
		if ($info ['shipping_status'] > 0) {
			$this->_ajm ( '300', '已发货无需在发！' );
		}
		// 添加订单发货记录信息
		$this->assign ( 'id', $id );
		$this->display ();
	}
	/**
	 * 处理发货信息
	 */
	function do_sipping() {
		// 修改订单状态
		$id = intval ( $_REQUEST ['id'] );
		$courier_number = $_REQUEST ['courier_number'];
		if (empty ( $courier_number )) {
			$this->_ajm ( '300', '快递单号不能为空！' );
		}
		
		// 添加订单发货记录信息
		$OrderExt = M ( 'OrderExt' );
		$sippingdata = array ();
		$sippingdata ['element'] = "courier_number"; // 扩展信息标识
		$sippingdata ['value'] = $courier_number; // 扩展信息的值
		$sippingdata ['name'] = "快递单号"; // 扩展信息名称
		$sippingdata ['order_id'] = $id; // 关联订单
		$res2 = $OrderExt->add ( $sippingdata );
		if (empty ( $res2 )) {
			$this->_ajm ( '300', '操作失败' );
		}
		
		// 获取订单当前信息
		$order = M ( 'Order' );
		$data = array ();
		$data ['id'] = $id;
		$data ["shipping_status"] = 1;
		$data ["mtime"] = mktime ();
		$data ["shipping_time"] = mktime ();
		$res1 = $order->save( $data );
		if (empty ( $res1 )) {
			$this->_ajm ( '300', '操作失败' );
		}
		
		$this->_ajm ( '200', '操作成功', 1 );
	} // end status
	
	/**
	 * 添加订单的备注信息
	 * @date 2013-6-29
	 * @time 上午10:57:39
	 */
	function add_msg() {
		// 添加订单的备注信息
		$id = intval ( $_REQUEST ['id'] );
		if (empty ( $id )) {
			$this->_ajm ( '300', '请先选择一个订单' );
		}
		$data = $this->ods->order_detail ( $id );
		$this->assign ( "info", $data );
		$this->assign ( 'order_id', $id );
		$this->display ();
	} // end add_msg
	
	/**
	 * 添加订单的备注信息
	 * @date 2013-7-1
	 * @time 下午12:44:45
	 */
	function do_msg() {
		// 添加订单的备注信息
		$userid = $this->_userid;
		$dao = M ( 'OrderLogs' );
		$_POST ['ctime'] = time ();
		$_POST ['user_id'] = $this->_userid;
		parent::insert ( $dao );
	} // end do_msg
	
	/**
	 * 查看订单的备注信息
	 * @date 2013-7-3
	 * @time 下午11:35:36
	 */
	function show_msg() {
		// 查看订单的备注信息
		$id = intval ( $_REQUEST ['id'] );
		if (empty ( $id )) {
			$this->_ajm ( '300', '请先选择一个订单' );
		}
		$data = $this->ods->order_detail ( $id );
		$this->assign ( "info", $data );
		$this->assign ( 'order_id', $id );
		$dao = M ( 'OrderLogs' );
		$map = array ();
		$map ['order_id'] = $id;
		parent::index ( $map, $dao );
	} // end show_msg
	
	/**
	 * 订单商品询价
	 * @date 2013-6-29
	 * @time 下午2:32:40
	 */
	function suppliers() {
		// 订单商品询价
		$ids = $_REQUEST ['ids'];
		// 获取订单内的商品
		if (is_array ( $ids )) {
			$ids = implode ( ',', $ids );
		}
		$ordergoods = M ( 'OrderGoods' );
		$ordersup = M ( 'OrderSuppliersPrice' );
		$goods = $ordergoods->where ( array (
				'order_id' => array (
						'IN',
						$ids 
				) 
		) )->select ();
		if (empty ( $goods )) {
			$this->_ajm ( '301', '获取商品信息错误' );
		}
		$pids = array ();
		$gids = array ();
		$temp = array ();
		foreach ( $goods as $good ) {
			$pids [] = $good ['product_id'];
			$gids [] = $good ['id'];
			$temp [$good ['order_id']] [$good ['product_id']] = $good;
		}
		$goods = $temp;
		
		// 查询商品是否已经确定供应商
		$where = array ();
		$where ['goods_id'] = array (
				'IN',
				implode ( ',', $gids ) 
		);
		$osp = $ordersup->where ( $where )->select ();
		$temp = array ();
		if (! empty ( $osp )) {
			foreach ( $osp as $v ) {
				$temp [$v ['goods_id']] [] = $v;
			}
		}
		$this->assign ( 'osp', $temp );
		
		// 获取供应商对应产品的价格
		$dao = D ( "ProductPriceListView" );
		$where = array ();
		$where ['id'] = array (
				'IN',
				implode ( ',', $pids ) 
		);
		$where ['pplstatus'] = array (
				'EQ',
				1 
		); // 价格必须是有效的
		$pgp = $dao->where ( $where )->select ();
		if (empty ( $pgp )) {
			$this->_ajm ( "300", '供应商价格获取错误' );
		}
		// echo($dao->getLastSql());
		$pgp = field2key ( $pgp, 'id' );
		$this->assign ( 'list', $goods );
		$this->assign ( 'pgp', $pgp );
		$this->display ();
		// 获取不同供应商的商品价格 暂时不做 目前只做一个供应商的情况
	} // end suppliers
	
	/**
	 * 处理供应商有货缺货信息
	 * @date 2013-7-4
	 * @time 上午11:25:53
	 */
	function do_suppliers() {
		// 处理供应商有货缺货信息
		$oid = intval ( $_REQUEST ['oid'] ); // 订单
		$pid = intval ( $_REQUEST ['pid'] ); // 产品
		$gid = intval ( $_REQUEST ['gid'] ); // 订单内的商品ID
		$status = intval ( $_REQUEST ['status'] ); // 状态
		$sid = intval ( $_REQUEST ['sid'] ); // 供应商
		$num = intval ( $_REQUEST ['num'] );
		$price = floatval ( $_REQUEST ['price'] ) * 100;
		$ppl = M ( 'ProductPriceList' );
		$os = M ( 'OrderSuppliersPrice' );
		$osdata = array ();
		$osdata ['order_id'] = $oid;
		$osdata ['suppliers_id'] = $sid;
		$osdata ['goods_id'] = $gid;
		$osinfo = $os->where ( $osdata )->find ();
		$st = true;
		$osdata ['status'] = $status;
		if (empty ( $osinfo )) {
			$osdata ['buy_price'] = $price;
			$osdata ['num'] = $num;
			$res = $os->add ( $osdata );
			$st = empty ( $res ) ? false : $st;
		} else {
			$osdata ['id'] = $osinfo ['id'];
			$osdata ['buy_price'] = $price;
			$res = $os->save ( $osdata );
			$st = $res === false ? false : $st;
		}
		// 查询供应商的价格
		$where = array ();
		$where ['status'] = 1;
		$where ['suppliers_id'] = $sid;
		$where ['product_id'] = $pid;
		$pplinfo = $ppl->where ( $where )->order ( 'create_date DESC' )->find ();
		if ($status == 1 && $st) {
			if ($pplinfo ['price1'] != $price && ! empty ( $pplinfo )) {
				// 有供货商信息，但是价格不一致，则修改供应商的价格
				$pplinfo ['status'] = 0;
				$res = $ppl->save ( $pplinfo );
				$st = $res === false ? false : $st;
				$pplinfo ['status'] = 1;
				$pplinfo ['price1'] = $price;
				$pplinfo ['create_uid'] = $this->_userid;
				$pplinfo ['create_date'] = time ();
				unset ( $pplinfo ['id'] );
				$res = $ppl->add ( $pplinfo );
				$st = empty ( $res ) ? false : $st;
			} elseif (empty ( $pplinfo )) {
				// 没有产品的供应商价格，添加供应价格
				$ppldata = array ();
				$ppldata ['suppliers_id'] = $sid;
				$ppldata ['product_id'] = $pid;
				$ppldata ['create_uid'] = $this->_userid;
				$ppldata ['create_date'] = time ();
				$ppldata ['qty1'] = 1;
				$ppldata ['price1'] = $price;
				$ppldata ['status'] = 1;
				$res = $ppl->add ( $ppldata );
				$st = empty ( $res ) ? false : $st;
			}
		} elseif (! empty ( $pplinfo ) && $st) {
			// 设置缺货时，同时设置供应商的价格无效
			$pplinfo ['status'] = 0;
			$res = $ppl->save ( $pplinfo );
			$st = $res === false ? false : $st;
		}
		if ($st) {
			$ordersup = M ( 'OrderSuppliersPrice' );
			$where = array ();
			$where ['goods_id'] = array (
					'EQ',
					$gid 
			);
			$osp = $ordersup->where ( $where )->select ();
			// dump($ordersup->getLastSql());
			$ospstr = '';
			if (! empty ( $osp )) {
				foreach ( $osp as $vs ) {
					if ($vs ['status'] == 1) {
						$ospstr .= number_format ( $vs ['buy_price'] / 100, 2, '.', '' ) . '/' . $vs ['num'] . ' 确认<br>';
					} else {
						$ospstr .= number_format ( $vs ['buy_price'] / 100, 2, '.', '' ) . '/' . $vs ['num'] . ' 无效<br>';
					}
				}
			}
		}
		$res = array ();
		if ($st) {
			$res ['status'] = 200;
			$res ['msg'] = $ospstr;
		} else {
			$res ['status'] = 300;
			$res ['msg'] = '操作不成功';
		}
		echo json_encode ( $res );
	} // end do_suppliers
	
	/**
	 * 获取出库单号
	 * @date 2013-8-16
	 * @time 下午2:30:30
	 *
	 * @param array $oids
	 *        	订单编号 | 产品编号 | 购物车商品编号 的数组
	 * @param string $field
	 *        	订单编号 | 产品编号 | 购物车商品编号 的字段名称
	 * @param
	 *        	return array
	 */
	function getdepot($oids = array(), $field = 'order_id') {
		// 获取订单的出库单号
		if (empty ( $oids ))
			return false;
		$where = array ();
		if (is_array ( $oids )) {
			$where [$field] = array (
					'IN',
					implode ( ',', $oids ) 
			);
		} else {
			$where [$field] = $oids;
		}
		$where ['status'] = array (
				'GT',
				0 
		);
		$dao = M ( 'Depot' );
		$depot = $dao->field ( 'code,order_id,product_id,goods_id' )->where ( $where )->group ( $field )->select ();
		return field2key ( $depot, $field );
	} // end getdepot
	
	/**
	 * 设置产品的供应商及有货无货情况
	 * @date 2013-8-1
	 * @time 下午4:36:10
	 */
	function setgoods() {
		// 设置产品的供应商及有货无货情况
		$this->display ();
	} // end setgoods
	
	/**
	 * 标记一个商品缺货
	 * @date 2013-8-14
	 * @time 下午5:50:43
	 */
	function oos() {
		$orderid = intval ( $_REQUEST ['id'] );
		$goods = $this->ods->order_goods ( $orderid );
		$this->assign ( 'goods', $goods );
		$finance = $this->ods->order_finance ( $orderid, 'OOS,REFUND' );
		$goods_finance = field2key ( $finance, 'goods_id', 2 );
// 		dump($goods);
// 		dump($finance);
// 		dump($goods_finance);
// 		exit();
		$this->assign ( 'finance', $finance );
		$this->assign ( 'goods_finance', $goods_finance );
		$this->display ();
	} // end oos
	
	/**
	 * 处理缺货
	 * @date 2013-8-30
	 * @time 下午4:19:10
	 */
	function do_oos() {
		// 处理缺货
		$id = intval ( $_REQUEST ['id'] );
		$porid = intval ( $_REQUEST ['porid'] );
		
		$number = intval ( $_REQUEST ['number'] );
		$tonumber = intval ( $_REQUEST ['tonumber'] );
		// 核查产品数额
		$goodsdao = M ( "OrderGoods" );
		$financedao = M ( "OrderFinance" );
		// 查询商品数量及价格
		$goods = $goodsdao->field ( 'id,price,product_name,product_id,order_id,number' )->where ( array (
				'id' => $id 
		) )->find ();
		$order = M ( "Order" )->find ( $goods ['order_id'] );
		if (empty ( $goods )) {
			$this->_ajm ( '300', '获取商品信息错误' );
		}
		// 查询以退款情况
		$where = array ();
		$where ['action'] = array (
				'IN',
				'OOS,REFUND' 
		);
		$where ['goods_id'] = array (
				'EQ',
				$porid 
		);
		$where ['order_id'] = array (
				'EQ',
				$goods ['order_id']
		);
		$fina = $financedao->where ( $where )->select ();
// 		$this->_ajm ( '300', $financedao->getLastSql() );
		$num = $goods ['number'];
		$pri = $goods ['price']; // 退款金额
		                         // 写入财务表
		if (! empty ( $fina )) {
			// 获取有效的商品数量
			foreach ( $fina as $vo ) {
				if ($vo ['action'] == 'OOS') {
					$num = $num - $vo ['number'];
				} elseif ($vo ['action'] == 'REFUND' && $vo ['subject'] == 'CV') {
					// 退款只退CV BV及MV只能赠送
					$pri = $pri - $vo ['value'];
				}
			}
		}
		// $this->_ajm ( '300', $num.'操作成功。'.$number,0);
		// echo $num ."----". $number;
		// exit();
		// 检查商品数量及价格
		if ($num < $tonumber) {
			// 缺货的数量大于实际数量啦
			$this->_ajm ( '300', '缺货退款的商品数量不能大于采购数' );
		}
		// if($num != $number){
		// $this->_ajm ( '300', '缺货退款的商品数量与可退款商品的数量不一致' );
		// }
		// if($num != $number){
		// $this->_ajm ( '300', '缺货退款的商品数量与可退款商品的数量不一致' );
		// }
		if (! $pri > 0) {
			$this->_ajm ( '300', '商品可退款已经为0' );
		}
		$finance = array ();
		$finance ['order_id'] =$goods ['order_id'];
		$finance ['action'] ='OOS';
		$finance ['goods_id'] = $porid;
		$finance ['number'] = $tonumber;
		$finance ['action_userid'] = $this->userid;
		$finance ['userid'] = $order ['userid'];
		$finance ['platform'] = 'SMW01';
		$finance ['subject'] = 'CV';
		$finance ['value'] = $pri;
		$finance ['status'] = 0;
		$finance ['code'] = 0;
		$finance ['remark'] = '产品' . $goods ['product_id'] . '[' . $goods ['product_name'] . ']缺货';
		$finance ['ctime'] = time ();
		$finance ['cip'] = get_client_ip ();
		$res = $financedao->add ( $finance );
		if ($res === false) {
			$this->_ajm ( '300', '写入数据失败，请重试。' );
		} else {
			$this->order->logs($order ['userid'],$goods ['order_id'],$finance ['remark'],$opt=array('open'=>'SYS','type'=>'oos'));
			$this->_ajm ( '200', '操作成功。', 0 );
		}
	} // end do_oos
	
	
	/**
	 * 拆单
	 * @date 2014.04.08
	 * @time 下午5:50:43
	 */
	function separate () {
		//注销key值
		unset($_SESSION['separatekey']);
		$separatekey =  'SEPARATEKEY'.date('YmdHis');		
		$orderid = intval ( $_REQUEST ['id'] );
		$goods = $this->ods->order_goods ( $orderid );
		$this->assign ( 'goods', $goods );
		$finance = $this->ods->order_finance ( $orderid, 'OOS,REFUND' );
		$goods_finance = field2key ( $finance, 'goods_id', 2 );
		// 		dump($goods);
		// 		dump($finance);
		// 		dump($goods_finance);
		// 		exit();
		$this->assign ( 'finance', $finance );
		$this->assign ( 'goods_finance', $goods_finance );
		$this->assign('oid',$orderid);
		$this->assign('separatekey',$separatekey);
		$this->display ();
	} // end oos
	
	
	function do_separate(){
		$separatekey = $_POST['separatekey'];
		if(!empty($_SESSION['separatekey'])){
			if($_SESSION['separatekey']==$separatekey){
				$this->_ajm(300,'请不要重复提交！');
			}
		}else{
			$_SESSION['separatekey'] = $separatekey;
		}
		
		$oldoid = $_REQUEST['oid'];
		$proid = $_REQUEST['proid'];
		$proprice = $_REQUEST['proprice'];
		$proname = $_REQUEST['proname'];
		$proimg = $_REQUEST['proimg'];
		$procode = $_REQUEST['procode'];
		$promname = $_REQUEST['promname'];
		$ossnum = $_REQUEST['ossnum'];
		if(empty($oldoid[0]) || empty($proid[0]) || emptyarray($ossnum) ){
			$this->_ajm(300,'数据不完整，不能进行拆单！（其中有参数为空,请检查数据，如不能解决请联系技术部！）');
			exit;
		}
	
		
		//获取订单信息
		$dao = M("Order");
		$order = $dao->find($oldoid);
				
		//*********************  begin 缺货操作***********************//
		$info = array();
		$info['order_id'] = $oldoid;
		$info['userid'] = $order['userid'];
		$info ['platform'] = 'SMW01';
		$ip = get_client_ip ();
		$this->order = new Order ( $info, $order['userid'], $ip, 'SMW01' );
		for($i=0;$i<count($proid);$i++){
			if($ossnum[$i]>0){
				$finance[]=array('action'=>'OOS','action_userid'=>$this->userid,'subject'=>'CV','value'=>$proprice[$i],'goods_id'=>$proid[$i],'remark'=>'产品'.$proid[$i].'['.$proname[$i].']缺货','code'=>'0','status'=>'1','number'=>$ossnum[$i]);			
			}			
		}
		$res = $this->order->w_finance($finance,$order['userid']);
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['debug']);
		}
		//*********************  end 缺货操作***********************//
		
		
		//*********************  begin 拆单操作  ***********************//
		//计算拆单总价格、总数量
		for($i=0;$i<count($proid);$i++){
			if($ossnum[$i]>0){
				$amount += $ossnum[$i]*$proprice[$i];
				$countnum += $ossnum[$i];
			}
		}
		
		$model = M("OrderFinance");
		$sql = "update order_finance set `value` = `value`-$amount where order_id = $oldoid and action = 'BUY' and code = 'spotprice' and subject = 'CV';";
		$res = $model->query($sql);
		if($res === false){
			$this->_ajm(300,'更新订单财务总金额操作失败！'.$sql);
			exit;
		}
		
		//****初始化订单信息
		$info = array ();
		$info['order_id'] = '';
		$info['userid'] = $order['userid'];
		$info['pay_status'] = 2;
		$info ['platform'] = 'SMW01';
		$info['shipping_status'] = 0;
		$info ['amount'] = $amount;
		$info ['count_num'] = $countnum;
		$ip = get_client_ip ();
		$this->order = new Order ( $info, $order['userid'], $ip, 'SMW01' );
		
		//****写入订单
		$res = $this->order->w_order();
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['data']);
		}else{
			$oid = $res['oid'];
		}
			
		//****写入 日志 order_logs
		$reid = $this->order->logs($order['userid'],$oid,'拆单',$opt=array('open'=>'User','type'=>'separate'));
		if(!$reid){
			$this->_ajm(300,"订单:$oid 写入日志表失败！请截图联系技术部！");
		}
		
		//****写入订单扩展  order_ext
		$model = M("OrderExt");
		$data = array();
		$data['element'] = 'separate';
		$data['value'] = 1;
		$data['name'] ='拆单';
		$data['order_id'] = $oid;
		$reid = $model->add($data);

		$data['element'] = 'pid';
		$data['value'] = $oldoid;
		$data['name'] ='父订单';
		$data['order_id'] = $oid;
		$reid = $model->add($data);
		if(!$reid){
			$this->_ajm(300,"订单:$oid 写入扩展表失败！请截图联系技术部！sql 日志：".$model->getLastSql());
			exit;
		}
		$this->order->logs($order ['userid'],$oldoid,'此订单已经被拆单处理',$opt=array('open'=>'SYS','type'=>'oostoseparate'));
		//****写入订单商品  order_goods
		$finance=array();
		$model = M("OrderGoods");
		for($i=0;$i<count($proid);$i++){
			if($ossnum[$i]>0){
				$data = array();
				$data['order_id'] = $oid;
				$data['product_id'] = $proid[$i];
				$data['product_thumb'] = $proimg[$i];
				$data['product_name'] = $proname[$i];
				$data['product_psn'] = $procode[$i];
				$data['price'] = $proprice[$i];
				$data['priceall'] = $proprice[$i]*$ossnum[$i];
				$data['number'] = $ossnum[$i];
				$data['mname'] = $promname[$i];
				$reid = $model->add($data);
				if($reid === false){
					$resstr .= '订单：'.$oid.'| 商品：'.$proid[$i].',';
				}
				$finance[]=array('action'=>'BUY','subject'=>'BV','value'=>0,'remark'=>'单件退货价格BV','code'=>'refund','status'=>'0','number'=>'1','goods_id'=>$proid[$i]);
				$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$proprice[$i],'remark'=>'单件退货价格CV','code'=>'refund','status'=>'0','number'=>'1','goods_id'=>$proid[$i]);
			}
		}
		if($resstr){
			$this->_ajm(300,$resstr.'写入订单商品失败！请截图联系技术部！');
			exit;
		}
		
		//*****写入订单地址  order_address
		$model = M("OrderAddress");
		$where['order_id'] = $oldoid;
		$oaddr = $model->field ('consignee,province,city,district,address,mobile,tel,email' )->where($where)->find ();
	//	$address = $model->field ('name consignee,province,city,area district,address,mobile,tel,email' )->find ();
		$this->order->chk_address ( $oaddr );
		$res = $this->order->w_address();
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['data']);
		}
		
		//**** 写入订单财务  order_finance
		$model = M("OrderFinance");		
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'商品总价','code'=>'amount','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'实际支付价','code'=>'reality','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'BV','value'=>0,'remark'=>'实际支付价','code'=>'reality','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'订单当前价格CV','code'=>'spotprice','status'=>'0','number'=>'0');
		$finance[]=array('action'=>'BUY','subject'=>'BV','value'=>0,'remark'=>'订单当前价格BV','code'=>'spotprice','status'=>'0','number'=>'0');
		//产品财务信息

		$res = $this->order->w_finance($finance,$order['userid']);
		
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['debug']);
		}
		
		//更新订单号
		$sn = '10' . date ( 'ymdH' ) . $oid;
		$data = array();
		$data['id'] = $oid;
		$data['sn'] = $sn;
		$reid = $dao->save($data);
		if($reid){			
			$this->_ajm(200,'操作成功！');
		}else{
			$this->_ajm(300,'操作失败！');
		}	
		
		//*********************  begin 拆单操作  ***********************//	
	}
	
	/**
	 * 标记补发
	 */
	function reissue(){
		$oid = $_REQUEST['id'];
		//****写入订单扩展  order_ext
		$model = M("OrderExt");
		$data = array();
		$data['element'] = 'reissue';
		$data['value'] = 1;
		$data['name'] ='补发';
		$data['order_id'] = $oid;
		$reid = $model->add($data);
		if($reid){
			$this->_ajm(200,'操作成功！',1);
		}else{
			$this->_ajm(300,'操作失败！');
		}
	}
	
	
	/**
	 * 替换产品
	 * @date 2014.04.08
	 * @time 下午5:50:43
	 */
	function ogoods () {
		//注销key值
		unset($_SESSION['ogoodskey']);
		$ogoodskey =  'OGOODSKEY'.date('YmdHis');
		$orderid = intval ( $_REQUEST ['id'] );
		$goods = $this->ods->order_goods ( $orderid );
		$this->assign ( 'goods', $goods );
		$finance = $this->ods->order_finance ( $orderid, 'OOS,REFUND' );
		$goods_finance = field2key ( $finance, 'goods_id', 2 );
		// 		dump($goods);
		// 		dump($finance);
		// 		dump($goods_finance);
		// 		exit();
		$this->assign ( 'finance', $finance );
		$this->assign ( 'goods_finance', $goods_finance );
		$this->assign('oid',$orderid);
		$this->assign('ogoodskey',$ogoodskey);
		$this->display ();
	} // end oos
	
	
	function do_ogoods(){
		$separatekey = $_POST['ogoodskey'];
		if(!empty($_SESSION['ogoodskey'])){
			if($_SESSION['ogoodskey']==$separatekey){
				$this->_ajm(300,'请不要重复提交！');
			}
		}else{
			$_SESSION['ogoodskey'] = $separatekey;
		}
		
		$oldoid = $_REQUEST['oid'];
		$proid = $_REQUEST['proid'];
		$proprice = $_REQUEST['proprice'];
		$proname = $_REQUEST['proname'];
		$pronum = $_REQUEST['pronum'];
		$newpronum = $_REQUEST['newpronum'];
		$newproid = array();
		foreach ($proid as $pid){
			if($_REQUEST['product'.$pid.'_id']){
				$newproid[$pid] = $_REQUEST['product'.$pid.'_id'];
			}
		}
		$model = M("Product");
		$where['id'] = array('in',implode(',', $newproid));
		$newproduct = $model->where($where)->select();
		$newproduct = field2key($newproduct,'id');
		
		//判断数据完整性
		if(empty($oldoid[0]) || empty($proid[0]) || empty($newproid)){
			$this->_ajm(300,'数据不完整，不能更换产品！（其中有参数为空，请仔细检查数据！如还不能解决，请联系技术部！）');
			exit;
		}
		
		//判断价格
		for($i=0;$i<count($proid);$i++){
			if($newproid[$proid[$i]]){
				if($newpronum[$i]<=0){
					$this->_ajm(300,'更换产品数量要大于0');
					exit;
				}
				if($proprice[$i]*$pronum[$i] < $newproduct[$newproid[$proid[$i]]]['price']*$newpronum[$i]){
					$this->_ajm(300,'更换产品（PID:'.$newproid[$proid[$i]].'）总价格,不能大于原来产品（PID:'.$proid[$i].'）的总价格！（总价格 = 单价 * 数量）');
					exit;
				}
			}
		}				
		
		//获取订单信息
		$dao = M("Order");
		$order = $dao->find($oldoid);
		
		//*********************  begin 缺货操作***********************//
		$info = array();
		$info['order_id'] = $oldoid;
		$info['userid'] = $order['userid'];
		$info ['platform'] = 'SMW01';
		$ip = get_client_ip ();
		$this->order = new Order ( $info, $order['userid'], $ip, 'SMW01' );
		for($i=0;$i<count($proid);$i++){
			$newpid = empty($newproid[$proid[$i]]) ? '' : $newproid[$proid[$i]] ;	
			if($newpronum[$i]>0 && $newpid){
				$finance[]=array('action'=>'OOS','action_userid'=>$this->userid,'subject'=>'CV','value'=>$proprice[$i],'goods_id'=>$proid[$i],'remark'=>'产品'.$proid[$i].'['.$proname[$i].']缺货','code'=>'0','status'=>'1','number'=>$pronum[$i]);			
				$c_price = ($proprice[$i]*$pronum[$i])-($newpronum[$i]*$newproduct[$newpid]['price']);
				$finance[]=array('action'=>'REFUND','action_userid'=>$this->userid,'subject'=>'CV','value'=>$c_price,'goods_id'=>$proid[$i],'remark'=>'产品'.$proid[$i].'['.$proname[$i].']退差价','code'=>'0','status'=>'0','number'=>1);
			}
		}
		$res = $this->order->w_finance($finance,$order['userid']);
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['debug']);
		}
		
		//****写入订单商品  order_goods
		$model = M("OrderGoods");
		$amount = 0 ; //新的商品总价格
		$chaprice = 0 ; //差价
		for($i=0;$i<count($proid);$i++){
			$newpid = $newproid[$proid[$i]];
			if($newpronum[$i]>0 && $newpid){
				$data = array();
				$data['order_id'] = $oldoid;
				$data['product_id'] = $newpid;
				$data['product_thumb'] = $newproduct[$newpid]['image'];
				$data['product_name'] = $newproduct[$newpid]['name'];
				$data['product_psn'] = $newproduct[$newpid]['code'];
				$data['price'] = $newproduct[$newpid]['price'];
				$data['priceall'] = $newproduct[$newpid]['price']*$newpronum[$i];
				$data['number'] = $newpronum[$i];
				$data['mname'] = $newproduct[$newpid]['mname'];
				$reid = $model->add($data);
				if($reid === false){
					$resstr .= '订单：'.$oldoid.'| 商品：'.$proid[$i].',';
				}
				$amount += $data['priceall'];
				$chaprice += $pronum[$i]*$proprice[$i] - $amount;
			}
		}
		if($resstr){
			$this->_ajm(300,$resstr.'写入订单商品失败！请截图联系技术部！');
			exit;
		}
		
		//************* 更新财务订单总金额
		$model = M("OrderFinance");
		$code = array('amount','reality','reality','spotprice');
		$subject = array('CV','CV','BV','CV');	
		$w = " where order_id = $oldoid and action = 'BUY'";
		for($j=0;$j<count($code);$j++){		
			$addvalue = $amount;
			$ww = '';
			$ww .= " and code = '".$code[$j]."' and subject = '".$subject[$j]."'"; 

			if($subject[$j]=='BV'){
				$addvalue = 0;
			}
			
			$sql = "update order_finance set `value` = `value`+$addvalue  ".$w.$ww ;
			
			if($code[$j] == 'spotprice'){		
						
				$sql = "update order_finance set `value` = `value`-$chaprice  ".$w.$ww ;
			}
			
			$res = $model->query($sql);
			if($res === false){
				$this->_ajm(300,'更新订单财务总金额操作失败！');
				exit;
			}
		}
		
		//************* 更新订单总金额
		$sql = "update `order` set amount = amount + ".$amount ." where id = ".$oldoid;
		$res = M()->query($sql);
		if($res === false){
			$this->_ajm(300,'更新订单总金额操作失败！');
			exit;
		}
		
		$this->_ajm(200,'操作成功！');
		//*********************  end 缺货操作***********************//
	}
	
	/**
	 * 处理退款
	 * @date 2013-8-30
	 * @time 下午4:19:10
	 */
	function do_refund() {
		// 处理缺货
		$id = intval ( $_REQUEST ['id'] );
		$porid = intval ( $_REQUEST ['porid'] );
	
		$number = intval ( $_REQUEST ['number'] );
		$money = intval ( $_REQUEST ['money'] ) * 100;
		// 核查产品数额
		$goodsdao = M ( "OrderGoods" );
		$financedao = M ( "OrderFinance" );
		// 查询商品数量及价格
		$goods = $goodsdao->field ( 'id,price,product_name,product_id,order_id,number' )->where ( array (
				'id' => $id
		) )->find ();
		if (empty ( $goods )) {
			$this->_ajm ( '300', '获取商品信息错误' );
		}
		$order = M ( "Order" )->find ( $goods ['order_id'] );
		$num = $goods ['number'];
		$pri = $goods ['price']; // 退款金额
		if($pri < $money){
			$this->_ajm ( '300', '退款金额不能大于商品卖价' );
		}
		// 写入财务表
		$finance = array (
				'order_id' => $goods ['order_id'],
				'action' => 'REFUND'
		);
		$finance ['goods_id'] = $porid;
		$finance ['number'] = $number;
		$finance ['action_userid'] = $this->userid;
		$finance ['userid'] = $order ['userid'];
		$finance ['platform'] = 'SMW01';
		$finance ['subject'] = 'CV';
		$finance ['value'] = $money;
		$finance ['status'] = 0;
		$finance ['code'] = 0;
		$finance ['remark'] = '产品' . $goods ['product_id'] . '[' . $goods ['product_name'] . ']退差价';
		$finance ['ctime'] = time ();
		$finance ['cip'] = get_client_ip ();
		$res = $financedao->add ( $finance );
		if ($res === false) {
			$this->_ajm ( '300', '写入数据失败，请重试。' );
		} else {
			$this->_ajm ( '200', '操作成功。', 0 );
		}
	} // end do_oos
	
	
	/**
	 * 生成出库单
	 * @date 2013-8-15
	 * @time 下午6:30:46
	 */
	function add_depot() {
		// 生成出库单
		$ids = $_REQUEST ['ids'];
		$dao = M ( "Depot" );
		$ogoods = M ( 'OrderGoods' );
		if (! empty ( $ids )) {
			$bhids = array ();
			foreach ( $ids as $k => $v ) {
				$where = array ();
				$where ['order_id'] = $v;
				$where ['status'] = array (
						'GT',
						0 
				);
				$res = $dao->where ( $where )->find ();
				if ($res) {
					$bhids [] = $v;
					unset ( $ids [$k] );
				}
			}
			if (empty ( $ids )) {
				$this->_ajm ( "300", 'ID为' . implode ( ',', $bhids ) . '的订单已经编入备货状态,请不要重复提交', 1 );
			}
			$ids = implode ( ',', $_REQUEST ['ids'] );
			$where = array ();
			$where ['order_id'] = array (
					'IN',
					$ids 
			);
			$goods = $ogoods->where ( $where )->select ();
			if (empty ( $goods )) {
				$this->_ajm ( '300', '获取商品信息错误' );
			}
			// 获取每个产品的供应商报价
			$where ['status'] = array (
					'GT',
					0 
			);
			$oldorder = $dao->field ( 'id,order_id' )->where ( $where )->select ();
			$oids = arr_to_explode ( $oldorder, 'id', '' );
			$static = array ();
			$static ['action_userid'] = $this->userid;
			$static ['status'] = 1;
			$static ['ctime'] = time ();
			$static ['code'] = date ( 'YmdH' );
			$static ['ymd'] = date ( 'Ymd' );
			$ids = array ();
			foreach ( $goods as $good ) {
				if (! in_array ( $good ['order_id'], $oids )) {
					$data = array ();
					$data = $static;
					$data ['order_id'] = $good ['order_id'];
					$data ['goods_id'] = $good ['id'];
					$data ['product_id'] = $good ['product_id'];
					$data ['number'] = $good ['number'];
					$ids [] = $dao->add ( $data );
				}
			}
			$this->_ajm ( "200", '订单已经编入备货状态', 1 );
		} else {
			$this->_ajm ( "300", '参数不能为空' );
		}
	} // end add_depot
	
	/**
	 * O2O订单结算
	 * @date 2013-12-9
	 * @time 下午5:53:05
	 */
	function o2ofee() {
		// O2O订单结算
		$where = array ();
		$where ['of.code'] = 'clearing';
		$where ['of.platform'] = '91YUNGOU';
		$where = self::create_where($where);
		
		$totalRows = M('OrderFinance')->join(" as of left join `order` on order.id=of.order_id")->where($where)->count ();
		$this->assign ( "totalCount", $totalRows );
		if ($totalRows > 0) {
			$page = new Page ( $totalRows );
			$pages = $page->show ();
			$m = M('OrderFinance');
			$orderfinance =$m->field('of.*,order.sn sn,order.platform platform,order.amount,order.add_time,order.status orstatus')->join(" as of left join `order` on order.id=of.order_id")->where($where)->order ( 'id DESC' )->limit( $page->firstRow . ',' . $page->listRows)->select();
			$this->assign ( 'pages', $pages );
			$this->assign ( 'list', $orderfinance );
		}
		$this->display ();
	} // end o2o_fee
	
	/**
	 * 处理O2O订单结算
	 */
	function do_o2ofee(){
		$id = intval ( $_REQUEST ['id'] );	
		$sn = $_REQUEST ['sn'];
		$platform =$_REQUEST ['platform'];
		
		$orfinance = M('OrderFinance')->where('id='.$id)->find ();
		//退款
		$msg = $this->cut_payment($sn,$orfinance['value'],0,$orfinance['userid'],$platform);
		if($msg){
			//更新状态
			$orderfinance = M('OrderFinance')->where('id='.$id)->save ( array ('status' => 1 ) );
			if (empty ( $orderfinance )) {
				$this->_ajm ( '300', '结算失败请重新结算。' );
			}
			$this->_ajm ( '200', '结算成功。', 1 );
		}else{
			$this->_ajm ( '300', '结算失败请重新结算。');
		}
		
		
		
	}
	
	/**
	 * PV|MV列表
	 * @author MaWei (http://www.phpyrb.com)
	 * @date 2014-2-13  下午6:01:42
	 */
	function bak(){
		$where = array();
		$where = self::create_where($where);
		$count = $this->newpro->pvmvinfo(null,$where);
		$page = new Page($count,$this->listrows);
		$limit = "$page->firstRow,$page->listRows";
		$info = $this->newpro->pvmvinfo($limit,$where);
		$this->assign('info',$info);
		$this->assign('staut',array('1'=>'已赠送','0'=>'未赠送'));
		$this->assign ( "totalCount", $count );
		$this->display();
	}
	
	/**
	 * 赠送PV｜MV，并写入记录
	 * @author MaWei (http://www.phpyrb.com)
	 * @date 2014-2-13  下午6:02:10
	 */
	function give(){
		$id = $_REQUEST['id'];
		$info = $this->newpro->pvmvlist('',$id);
		$bal = $this->newpro->balance($info['userid'],$info['subject'],$info['platform']);
		$model = M('UserAssets');
		$data = array();
		$data['userid'] = $info['userid'];
		$data['action_userid'] = $this->userid;
		$data['platform'] = $info['platform'];
		$data['subject'] = $info['subject'];
		$data['value'] = $info['value'];
		if($bal){
			$data['nowvalue'] = $bal[0]['value'];
		}else{
			$data['nowvalue'] = 0;
		}
		
		$data['ctime'] = time();
		$data['cip'] = get_client_ip();
		$data['bzvu'] = '赠送'.$info['subject'];
		$data['changtype'] = 'ORDER_USE';
		$reid = $model->add($data);
		$reid === false ? exit(0) : false;
		$text = array();
		$text['userid'] = $info['userid'];
		$text['subject'] = $info['subject'];
		$text['platform'] = $info['platform'];
		$text['value'] = $data['nowvalue'] + $info['value'];
		$text['mtime'] = time();
		$reid = M('UserMoney')->add($text,array(),true);
		$reid === false ? exit(0) : false;
		$reid = M('OrderFinance')->where(array('id'=>$id))->setField('status',1);
		$reid === false ? exit(0) : false;
		echo 1;
	}
	
	
	/**
	 * 批量赠送PV｜MV，并写入记录，赠送3天之前订单已完成并且未赠送的
	 * @date 2014-2-13  下午6:02:10
	 */
	function give_list(){
		
		//查询3天之前订单已完成并且未赠送的
		$sql="select of.* from `order` o LEFT JOIN order_finance of on of.order_id = o.id
		where (of.`subject` = 'PV' OR of.`subject` = 'MV') and of.`status` = 0 and o.`status` = 10 and FROM_UNIXTIME(o.mtime ,'%Y%m%d') < DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 3 DAY),'%Y%m%d')";
		$list = M()->query($sql);
		$status =true;
		foreach ($list as $v){
			
			//查询用户金额信息
			$info = $v;
			$where = array();
			$where['userid'] = $info['userid'];
			$where['subject'] = $info['subject'];
			$where['platfrom'] = $info['platform'];
			$bal = m('UserMoney')->where($where)->find();
			
			//插入流水
			$model = M('UserAssets');
			$data = array();
			$data['userid'] = $info['userid'];
			$data['action_userid'] = $this->userid;
			$data['platform'] = $info['platform'];
			$data['subject'] = $info['subject'];
			$data['value'] = $info['value'];
			if($bal){
				$data['nowvalue'] = $bal['value'];
			}else{
				$data['nowvalue'] = 0;
			}
			$data['ctime'] = time();
			$data['cip'] = get_client_ip();
			$data['bzvu'] = '赠送'.$info['subject'];
			$data['changtype'] = 'ORDER_USE';
			$reid = $model->add($data);
			if($reid===false){
				$status=false;
			}
			//更新金额
			$bal['value'] = $bal['nowvalue'] + $bal['value'];
			$bal['mtime'] = time();
			if($bal){
				$reid = M('UserMoney')->save($bal);
			}else{
				$bal['userid'] = $info['userid'];
				$bal['subject'] = $info['subject'];
				$bal['platform'] = $info['platform'];
				$reid = M('UserMoney')->add($bal);
			}
			if($reid===false){
				$status=false;
			}
			//修改赠送状态
			$v['status']=1;
			$reid = M('OrderFinance')->save($v);
			if($reid===false){
				$status=false;
			}
		}
		
		//$this->_ajm(300,'可赠送BV，但备注信息写入失败，请把该错误信息及订单号，发给技术部处理！');
		
		$this->_ajm ( 200, '操作成功', 1 );
	}
	
	
	
	/**
	 * 退款CV和BV
	 * @param CV $cvorder
	 * @param BV $bvorder
	 * @param ID $userid
	 * @return boolean
	 */
	function cut_payment($orderid,$cvorder,$bvorder,$userid,$platform){
	
		$usermoney=M('UserMoney');//用户金额
		$assetc_dao = M ( "UserAssets" );//流水
		$data=array();//数据集合
		$bvuser=0;//用户BV余额
		$cvuser=0;//用户CV余额
		$bvid = 0;//用户BV金额ID
		$cvid = 0;//用户CV金额ID
		//读取用户金额
		$usermoneys = M()->query( "select *	from user_money where userid = {$userid}" );
		foreach ($usermoneys as $um){
			//读取BV金额
			if($um['subject'] == 'BV' && $um['platform'] == $platform){
				$bvid=$um['id'];
				$bvuser = $um['value'];
			}
			//读取CV金额
			if($um['subject'] == 'CV' && $um['platform'] == $platform){
				$cvid=$um['id'];
				$cvuser = $um['value'];
			}
		}
		$assetc = array();
		$assetc['userid']=$userid;
		$assetc['action_userid']=$this->userid;//操作人员ID
		$assetc['platform']=$platform;//SMW01
		$assetc['ctime']=mktime();
		$assetc['cip']=get_client_ip();
		$assetc['bzvu']=$orderid;//备注信息:订单号、授权码、操作原因
		$assetc['changtype']='ORDER_FEE';//资金变动的原因 ORDER_USE ADMIN_ADD
		$usermoney->startTrans ();
		$assetc_dao->startTrans ();
	
		//更新BV金额
		$data["value"]=$bvuser+$bvorder;
		$assetc['value']=$bvorder;//变动数额
		$data['mtime']=mktime();
		if($bvid ==0){
			$data['platform']=$platform;
			$res=$usermoney->add($data);
		}else{
			$data["id"]=$bvid;
			$res=$usermoney->save($data);
		}
		
		if (!$res) {
			$usermoney->rollback ();
			return false;
		}
		// 写入充值流水
		$assetc['subject']='BV';//科目： BV CV CNY MV PV  COUPON
		$assetc['nowvalue']=$data["value"];//用户当前余额
		$assetc_id = $assetc_dao->add ( $assetc );
		if (!$assetc_id) {
			$usermoney->rollback ();
			$assetc_dao->rollback ();
			return false;
		}
	
		//更新CV金额
		$data["value"]=$cvuser + $cvorder;
		$data['mtime']=mktime();
		if($cvid ==0){
			$data['platform']=$platform;
			$res=$usermoney->add($data);
		}else{
			$data["id"]=$cvid;
			$res=$usermoney->save($data);
		}
		
		if (!$res) {
			$usermoney->rollback ();
			$assetc_dao->rollback ();
			return false;
		}
		// 写入充值流水
		$assetc['subject']='CV';//科目： BV CV CNY MV PV  COUPON
		$assetc['value']=$cvorder;//变动数额
		$assetc['nowvalue']=$cvuser + $cvorder;//用户当前余额
		$assetc_id = $assetc_dao->add ( $assetc );
		if (!$assetc_id) {
			$usermoney->rollback ();
			$assetc_dao->rollback ();
			return false;
		}
		$usermoney->commit ();
		$assetc_dao->commit ();
		return true;
	}
	/**
	 * 设置云购手续费
	 * @date 2013-10-21
	 * @time 下午2:49:46
	 */
	protected function _set_fee() {
		// 设置云购手续费
		$arr = array ();
		$arr ['sp'] = 0.03;
		$arr ['pj'] = 0.03;
		$arr ['sj'] = 0.02;
		$arr ['sj3k'] = 0.015;
		$arr ['pb'] = 0.02;
		$arr ['pb2k'] = 0.015;
		$arr ['lh'] = 0.03;
		$this->fee = $arr;
		$this->assign ( 'fee', $arr );
		$arr = array ();
		$arr ['sp'] = 0.04;
		$arr ['pj'] = 0.04;
		$arr ['sj'] = 0.03;
		$arr ['sj3k'] = 0.03;
		$arr ['pb'] = 0.03;
		$arr ['pb2k'] = 0.03;
		$arr ['lh'] = 0.04;
		$this->small_fee = $arr;
		$this->assign ( 'small_fee', $arr );
	} // end set_fee
	
	/**
	 * 获取产品的手续费
	 * @date 2013-10-21
	 * @time 下午3:12:44
	 *
	 * @param string $modelname
	 *        	产品类型 sp pj sj pb lh
	 * @param number $price
	 *        	产品价格1(分)
	 * @param number $site_type
	 *        	站点类型 1:云购商 2:云购店
	 * @return integer 产品手续费(分)
	 */
	protected function get_fee($modelname = '', $price = 0, $site_type = 0) {
		// 获取产品的手续费
		$arr = $site_type == 15 ? $this->fee : $this->small_fee;
		if ($modelname == 'sj') {
			if ($price > 300000) {
				$modelname = 'sj3k';
			}
		} elseif ($modelname == 'pb') {
			if ($price > 200000) {
				$modelname = 'pb2k';
			}
		}
		$fee = $arr [$modelname];
		if (empty ( $fee )) {
			return false;
		} else {
			return $price * $fee;
		}
	} // end get_fee
	
	/**
	 * 获取订单内商品的手续费
	 * @date 2013-11-11
	 * @time 下午4:41:38
	 *
	 * @param array $goods
	 *        	订单商品信息
	 */
	protected function get_order_fee($goods = array(), $site_type = 15) {
		// 获取订单内商品的手续费
		$fee = 0;
		foreach ( $goods as $v ) {
			$temp_fee = 0;
			$temp_fee = self::get_fee ( $v ['mname'], $v ['allsaleprice'], $site_type );
			if ($temp_fee) {
				$fee += $temp_fee;
			}
			if ($temp_fee === false) {
				return false;
			}
		}
		return $fee;
	} // end get_order_fee
	//批量到出送货单
	public function delivery() {
		if (array_key_exists("noprint", $_REQUEST)) {
			$this->assign("noprint", "1");
		}
		$ids = explode(',', array_shift($_REQUEST['ids']));
// 		$ids = explode(",", array_key_exists("ids", $_REQUEST)?$_REQUEST['ids']:$_REQUEST['id']);
		$ases = array();
		foreach($ids as $id) {
			$order = M ( 'Order' )->find($id);
			if (! $order && $order ['userid'] != $this->_userid)
				$this->success ( L ( 'do_empty' ) );
	
			$order_data = M ( 'Order_data' )->where ( "order_id='{$order[id]}' and is_ok=1" )->select ();
			$amount = 0;
			$jiazs = 0;
			foreach ( $order_data as $key => $r ) {
				$amount = $amount + $r ['price'];
				$jiazs = $jiazs + $r ['jiazhengsong'];
			}
	
			$ases[$id]["order"] = $order;
			$ases[$id]["order_data"] = $order_data;
			$ases[$id]["amount"] = $amount;
			$ases[$id]["jiazs"] = $jiazs;
			$ases[$id]["aj"] = $amount - $jiazs;
	
			$userassets = M ( "UserAssets" );
			$where = array ();
			$where ['ordersn'] = array (
					'eq',
					$order ['sn']
			);
			$where ['userid'] = array (
					'eq',
					$order ['userid']
			);
			$where ['changtype'] = array (
					'eq',
					'ORDER_USE'
			);
			$assets = $userassets->where ( $where )->find ();
			$ases[$id]["assets"] = $assets;
	
			$cvs = $userassets->where ( "changtype<>'ORDER_USE' and ordersn=" . $order ['sn'] )->select ();
			$ases[$id]["cvs"] = $cvs;
	
		}
		$this->assign("ases", array_reverse($ases));
		$Area = M ( 'Area' )->getField ( 'id,name' );
		$this->assign("Area", $Area);
	
		$this->display ();
	}
	/**
	 * 获取用户最大权限的用户组
	 * @date 2013-12-9
	 * @time 下午6:38:30
	 */
	protected function _get_spu_level() {
		// 获取用户最大权限的用户组
		;
	} // end get_spu_level
	
	function coupon() {
		$dao = M("OrderCoupon");
		$map = array();
		$map['c.type'] = 'USE';
		$map['c.subject'] = 'CV';
		// 查看需要退款操作的订单
		$map = self::create_where($map);
		$count = $dao->join(" as c left join `order` as o on o.id = c.order_id ")->join("order_goods og on og.order_id = c.order_id and og.product_id = c.goods_id")->where($map)->count();
		
		$this->assign("totalCount",$count);
		if($count>0){
			$page=new Page($count,$this->listrows);
			$list = $dao->field("c.id couid, o.id order_id,o.sn,o.amount,o.add_time ctime,u.username,u.id userid,og.product_name `name`,og.number,og.priceall,c.value")
			->join(" as c left join `order` as o on o.id = c.order_id ")
			->join("order_goods og on og.order_id = c.order_id and og.product_id = c.goods_id")
			->join("user as u on u.id = c.userid")->limit($page->firstRow,$page->listRows)->where($map)->order("c.id desc")->select();
			$this->assign('list',$list);
			//echo $dao->getLastSql();
		}
        $this->display();
	}
	/**
	 * 采购单详情
	 */
	function order_goods(){
		$ids =  $_REQUEST['ids'];
		$this->assign('ids',$ids);
		
		$list=M()->query("select og.product_id product_id ,o.id id,FROM_UNIXTIME(o.add_time,'%Y年%m月%d日') add_time,o.sn sn,o.userid userid,og.mname mname,og.product_name product_name,og.number number,og.price price,og.priceall priceall,oc.`value` bvvalue
					from `order` o LEFT JOIN order_goods og on o.id = og.order_id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id where o.id in ($ids) order by o.id,og.product_id");
// 		echo M()->getLastSql();
// 		$ids =  explode(',', $_REQUEST['ids']);
// 		foreach ( $ids as $id ) {
// 			$ases [] = $this->ods->order_detail ( $id );
// 			$coupondata[$id] = M ()->query ( "select *	from order_coupon where order_id = {$id}" );
// 		}
// 		$this->assign ( 'coupondata',$coupondata);
	
		//获取缺货信息
		$dao = M("OrderFinance");
		$where['action'] = 'OOS';
		$where['order_id'] = array('IN',$ids);		
		//$res = $dao->field("order_id,action,`subject`,sum(`value`) as totalvalue,goods_id,sum(number) as number")->where($where)->group('goods_id')->order("order_id desc")->select();
		$res = $dao->field("order_id,action,`subject`,`value` as totalvalue,goods_id,number as number")->where($where)->order("order_id desc")->select();
		
		$finances = array();
		foreach ($res as $key=>$vo){
				$finances[$vo['order_id']][$vo['goods_id']] = $vo; 
		}
		
		foreach ($list as $key=>$vo){
			$data = $finances[$vo['id']][$vo['product_id']];
			if($data){
				$list[$key]['number'] -= $data['number'];
				if($list[$key]['number'] < 0){
					$list[$key]['unset'] == 1;
				}
				$list[$key]['priceall'] -= $data['totalvalue'];
			}
		}
		
		foreach ($list as $key =>$vo ){
			if($vo['unset']==1){
				unset($list[$key]);
			}
		}
		
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 采购单详情数据导出版
	 */
	function order_goods_import(){
		$ids =  $_REQUEST['ids'];
		$this->assign('ids',$ids);
		
		$list=M()->query("select og.product_id product_id ,o.id id,FROM_UNIXTIME(o.add_time,'%Y年%m月%d日') add_time,o.sn sn,o.userid userid,og.mname mname,og.product_name product_name,og.number number,og.price price,og.priceall priceall,oc.`value` bvvalue
				from `order` o LEFT JOIN order_goods og on o.id = og.order_id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id where o.id in ($ids) order by o.id,og.product_id");
		// 		echo M()->getLastSql();
// 		$ids =  explode(',', $_REQUEST['ids']);
// 		foreach ( $ids as $id ) {
// 			$ases [] = $this->ods->order_detail ( $id );
// 			$coupondata[$id] = M ()->query ( "select *	from order_coupon where order_id = {$id}" );
// 		}
// 		$this->assign ( 'coupondata',$coupondata);
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 采购单合并
	 */
	function order_mergegoods(){
		$ids =  $_REQUEST['ids'];
	
		$list=M()->query("SELECT og.product_id product_id,MIN(og.mname) mname,MIN(og.product_name) product_name,SUM(og.number) number,MIN(og.price) price,SUM(og.priceall) priceall,GROUP_CONCAT(o.id) order_id,GROUP_CONCAT(o.sn) sn,MIN(FROM_UNIXTIME(o.add_time,'%Y年%m月%d日')) add_time,SUM(oc.`value`) bvvalue
				from order_goods og LEFT JOIN `order` o on og.order_id = o.id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id where og.order_id in ($ids) GROUP BY og.product_id order by og.product_id");
//		echo M()->getLastSql();
// 		$ids =  explode(',', $_REQUEST['ids']);
// 		foreach ( $ids as $id ) {
// 			$ases [] = $this->ods->order_detail ( $id );
// 			$coupondata[$id] = M ()->query ( "select *	from order_coupon where order_id = {$id}" );
// 		}
		
		
// 		$this->assign ( 'coupondata',$coupondata);

		
		//获取缺货信息
		$dao = M("OrderFinance");
		$where['action'] = 'OOS';
		$where['order_id'] = array('IN',$ids);
		$res = $dao->field("order_id,action,`subject`,sum(`value`) as totalvalue,goods_id,sum(number) as number")->where($where)->group('goods_id')->order("order_id desc")->select();
		$finances = array();
		foreach ($res as $key=>$vo){
			$finances[$vo['goods_id']] = $vo;
		}
	
		foreach ($list as $key=>$vo){
			$data = $finances[$vo['product_id']];
			if($data){
				$list[$key]['number'] -= $data['number'];
				if($list[$key]['number'] <= 0){
					$list[$key]['unset'] == 1;
				}
				$list[$key]['priceall'] -= $data['totalvalue'];
			}
		}
		
		foreach ($list as $key =>$vo ){
			if($vo['unset']==1){
				unset($list[$key]);
			}
		}
		
		$this->assign('ids',$ids);
		$this->assign('list',$list);
		$this->display();
	}
	/**
	 * 采购单合并数据导出版
	 */
	function order_mergegoods_import(){
		$ids =  $_REQUEST['ids'];
		$this->assign('ids',$ids);
	
		$list=M()->query("SELECT og.product_id product_id,MIN(og.mname) mname,MIN(og.product_name) product_name,SUM(og.number) number,MIN(og.price) price,SUM(og.priceall) priceall,GROUP_CONCAT(o.id) order_id,GROUP_CONCAT(o.sn) sn,MIN(FROM_UNIXTIME(o.add_time,'%Y年%m月%d日')) add_time,SUM(oc.`value`) bvvalue
				from order_goods og LEFT JOIN `order` o on og.order_id = o.id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id where og.order_id in ($ids) GROUP BY og.product_id order by og.product_id");
// 		echo M()->getLastSql();
// 		$ids =  explode(',', $_REQUEST['ids']);
// 		foreach ( $ids as $id ) {
// 			$ases [] = $this->ods->order_detail ( $id );
// 			$coupondata[$id] = M ()->query ( "select *	from order_coupon where order_id = {$id}" );
// 		}
// 		$this->assign ( 'coupondata',$coupondata);
		
		$this->assign('list',$list);
		$this->display();
	}
	
	
	/**
	 * 客户添加订单那
	 * @author tb
	 * @date 2014.04.08
	 * */
	function orderdone(){
		$proids = $_REQUEST['proids'];
		$pronum = $_REQUEST['pronum'];
		$proimg = $_REQUEST['proimg'];
		$proname = $_REQUEST['proname'];
		$procode = $_REQUEST['procode'];
		$promname = $_REQUEST['promname'];
		$uid =  $_REQUEST['user_id'];
		$addrid = $_REQUEST['useraddr'];
		$proprice = $_REQUEST['proprice'];
		
		if(!$proids || !$pronum || !$proimg || !$proname || !$procode || !$promname || !$uid || !$addrid || !$proprice){
			$this->_ajm(300,'提交数据不完整，请检查数据，或者刷选后重试！');
			exit;
		}
		
		//计算总价格、总数量
		for($i=0;$i<count($proids);$i++){
			$amount += $pronum[$i]*$proprice[$i];
			$countnum += $pronum[$i];
		}
		$amount = $amount*100;
		
		//****初始化订单信息
		$info = array ();
		$info['order_id'] = '';
		$info['userid'] = $uid;
		$info['pay_status'] = 2;
		$info ['platform'] = 'SMW01';
		$info['shipping_status'] = 0;
		$info ['amount'] = $amount;
		$info ['count_num'] = $countnum;
		$ip = get_client_ip ();
		$this->order = new Order ( $info, $uid, $ip, 'SMW01' );
		
		//****写入订单
		$res = $this->order->w_order();
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['data']);
		}else{
			$oid = $res['oid'];
		}
			
		//****写入 日志 order_logs
		$reid = $this->order->logs($uid,$oid,'售后补货',$opt=array('open'=>'User','type'=>'userdone'));
		if(!$reid){
			$this->_ajm(300,"订单:$oid 写入日志表失败！请截图联系技术部！");
		}
		
		//****写入订单扩展  order_ext
		$model = M("OrderExt");
		$data = array();
		$data['element'] = 'userdone';
		$data['value'] = 1;
		$data['name'] ='售后补货';
		$data['order_id'] = $oid;
		$reid = $model->add($data);
		if(!$reid){
			$this->_ajm(300,"订单:$oid 写入扩展表失败！请截图联系技术部！sql 日志：".$model->getLastSql());
			exit;
		}
				
		//****写入订单商品  order_goods	
		$model = M("OrderGoods");
		for($i=0;$i<count($proids);$i++){
			$data = array();
			$data['order_id'] = $oid;
			$data['product_id'] = $proids[$i];
			$data['product_thumb'] = $proimg[$i];
			$data['product_name'] = $proname[$i];
			$data['product_psn'] = $procode[$i];
			$data['price'] = $proprice[$i]*100;
			$data['priceall'] = $proprice[$i]*$pronum[$i]*100;
			$data['number'] = $pronum[$i];
			$data['mname'] = $promname[$i];
			$reid = $model->add($data);
			if($reid === false){
				$resstr .= '订单：'.$oid.'| 商品：'.$proids[$i].',';
			}
		}	
		if($resstr){
			$this->_ajm(300,$resstr.'写入订单商品失败！请截图联系技术部！');
			exit;
		}
		
		//*****写入订单地址  order_address		
		$model = M("UserAddress");		
		$address = $model->field ('name consignee,province,city,area district,address,mobile,tel,email' )->find ($addrid);
		$this->order->chk_address ( $address );
		$res = $this->order->w_address();
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['data']);
		}
		
		//**** 写入订单财务  order_finance
		$model = M("OrderFinance");	
		$finance=array();
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'商品总价','code'=>'amount','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'实际支付价','code'=>'reality','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'BV','value'=>0,'remark'=>'实际支付价','code'=>'reality','status'=>'1','number'=>$countnum);
		$finance[]=array('action'=>'BUY','subject'=>'CV','value'=>$amount,'remark'=>'订单当前价格CV','code'=>'spotprice','status'=>'0','number'=>'0');
		$finance[]=array('action'=>'BUY','subject'=>'BV','value'=>0,'remark'=>'订单当前价格BV','code'=>'spotprice','status'=>'0','number'=>'0');
		$res = $this->order->w_finance($finance,$uid);
		
		if($res['status'] === 0){
			$this->_ajm(300,$res['msg']." debug:".$res['debug']);
		}
		
		//更新订单号
		$model = M("Order");
		$sn = '10' . date ( 'ymdH' ) . $oid;
		$data = array();
		$data['id'] = $oid;
		$data['sn'] = $sn;
		$reid = $model->save($data);
		
		if($reid){
			$this->_ajm(200,'添加成功！',1);
		}else{
			$this->_ajm(300,'添加失败！');
		}
		
	}
	
	/**
	 * 是否出库
	 */
	function order_shipping(){
		$ids =  $_REQUEST['ids'];
	
		$orderList=M()->query("select og.product_id product_id ,o.id id,FROM_UNIXTIME(o.add_time,'%Y年%m月%d日') add_time,o.sn sn,o.userid userid,og.mname mname,og.product_name product_name,og.number number,og.price price,og.priceall priceall
				from `order` o LEFT JOIN order_goods og on o.id = og.order_id where o.id in ($ids) order by o.id");
		// 		echo M()->getLastSql();
		$inventoryOrderList=M()->query("select * from inventory_order");
		$ids =  explode(',', $_REQUEST['ids']);
		sort($ids);
		$list=array();
		foreach ( $ids as $id ) {
			$order =array();
			$data=array();
			$orderLs=M()->query("select og.product_id product_id ,o.id id,FROM_UNIXTIME(o.add_time,'%Y年%m月%d日') add_time,o.sn sn,o.userid userid,og.mname mname,og.product_name product_name,og.number number,og.price price,og.priceall priceall
					from `order` o LEFT JOIN order_goods og on o.id = og.order_id where o.id = $id order by o.id");
			foreach ($orderLs as $ko => $obj){
				//库存是否足够
				$val=true;
				//库存是否有此款产品
				$isval=false;
				//检测库存
				foreach ($inventoryOrderList as $k => $iobj){
					if($obj['product_id'] == $iobj['productid']){
						$isval=true;
						if(($iobj['number']-$obj['number']) < 0){
							$val=false;
						}
					}
				}
				//验证
				if($val && $isval){
					$obj['istatr'][$ko]=1;
					$data[$obj['id']][$ko]=1;
				}else{
					$obj['istatr'][$ko]=0;
					$data[$obj['id']][$ko]=0;
				}
			}
			//是否可以出库
			$shifou=1;
			foreach ($data[$id] as $v){
				if($v==0){
					$shifou = 0;
				}
			}
			
			//验证是否可以出库，如果可以出库将减少库存
			if($shifou){
				foreach ($inventoryOrderList as $k => $iobj){
					if($obj['product_id'] == $iobj['productid']){
						if(($iobj['number']-$obj['number']) >= 0){
							$iobj['number']=$iobj['number']-$obj['number'];
							$inventoryOrderList[$k]=$iobj;
						}
					}
				} 
			}
			
			
			$order['id']=$id;
			$order['sn']=$orderLs[0]['sn'];
			$order['istatr']=$shifou;
			$list[]=$order;
		}
// 		$data =array();
// 		foreach ($orderList as $ko => $obj){
// 			$val=true;
// 			$isval=false;
// 			foreach ($inventoryOrderList as $k => $iobj){
// 				if($obj['product_id'] == $iobj['productid']){
// 					$isval=true;
// 					if(($iobj['number']-$obj['number']) < 0){
// 						$val=false;
// 					}else{
// 						$iobj['number']=$iobj['number']-$obj['number'];
// 						$inventoryOrderList[$k]=$iobj;
// 					}
// 				}
// 			}
// 			if($val && $isval){
// 				$obj['istatr'][$ko]=1;
// 				$data[$obj['id']]=$obj;
// 			}else{
// 				$obj['istatr'][$ko]=0;
// 				$data[$obj['id']]=$obj;
// 			}
// 		}
// 		dump($data);
		$this->assign('list',$list);
		$this->display();
	}
	/**
	 * 销售统计
	 */
	function sales_statistics(){
		if($_REQUEST['starttime'] && $_REQUEST['endtime']){
			$starttime = gettime($_REQUEST['starttime']." 00:00:00");
			$endtime = gettime($_REQUEST['endtime']." 23:59:59");
		}
		$list=M()->query("SELECT g.product_id product_id,g.product_name product_name,SUM(g.number) number,SUM(g.priceall) priceall,o.add_time add_time
							FROM order_goods AS g LEFT JOIN `order` as o  ON o.id=g.order_id	WHERE o.add_time> $starttime AND o.add_time< $endtime AND g.mname='sj'
								GROUP BY g.product_id ORDER BY number DESC");
		$this->assign('starttime',$_REQUEST['starttime']);
		$this->assign('endtime',$_REQUEST['endtime']);
		$this->assign('type',$_REQUEST['type']);
		$this->assign('list',$list);
		$this->display();
	}
	/**
	 * 销售统计明细
	 */
	function sales_statistics_detail(){
		$product_id=$_REQUEST['product_id'];
		$list=M()->query("SELECT o.id id,g.product_id product_id,g.product_name product_name,g.number number,g.priceall priceall,o.add_time add_time
						FROM  order_goods AS g LEFT JOIN `order` as o ON o.id=g.order_id WHERE g.product_id=$product_id ORDER BY number DESC");
		$this->assign('list',$list);
		$this->display();
	}
	/**
	 * 采购统计
	 */
	function procurement_statistics(){
		if($_REQUEST['starttime'] && $_REQUEST['endtime']){
			$starttime = gettime($_REQUEST['starttime']);
			$endtime = gettime($_REQUEST['endtime']);
		}
		$list=M()->query("select FROM_UNIXTIME(o.add_time,'%m月%d日') add_time,o.sn sn,(CASE og.mname WHEN 'sj' THEN '手机'
				WHEN 'pb' THEN '平板' ELSE '手机配件' END) as mname,og.product_name product_name,
				og.number number,og.price price,og.priceall priceall,oc.`value` BV,og.priceall priceall,'库存' as gys
				from `order` o LEFT JOIN order_goods og on o.id = og.order_id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id
				WHERE o.add_time> $starttime AND o.add_time< $endtime order by o.id,og.product_id");
				$this->assign('starttime',$_REQUEST['starttime']);
				$this->assign('endtime',$_REQUEST['endtime']);
				$this->assign('type',$_REQUEST['type']);
				$this->assign('list',$list);
				$this->display();
	}
	
	
}//end OrderAction